# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymongo
from WeatherChecker.settings import DB_HOST, DB_PORT


class WeathercheckerPipeline:
    def __init__(self):
        self.client = pymongo.MongoClient(DB_HOST, DB_PORT)
        self.db = self.client.get_database('Weather')

    def process_item(self, item, spider):
        collection = self.db.get_collection(item['region'])
        collection.update_one({'_id': item['_id']}, {
            "$set": dict(item)
        }, upsert=True)
        return item

    def close_spider(self, spider):
        self.client.close()
